package com.java;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 3个卖票员 卖30张票
 * 多想成的企业级套路+模板
 *
 * 1.在高内聚低耦合的前提下,线程           操作 (对外暴露调用的方法)                 资源类
 * @author jingjintao
 * @date 2021/10/23 - 17:43
 **/
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {for (int i = 1; i < 40; i++) ticket.saleTicket();},"A").start();
        new Thread(() -> {for (int i = 1; i < 40; i++) ticket.saleTicket();},"B").start();
        new Thread(() -> {for (int i = 1; i < 40; i++) ticket.saleTicket();},"C").start();


        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"C").start();*/
    }
}

class Ticket{ //资源类

    private int number = 30;

    private Lock lock = new ReentrantLock();

    public void saleTicket(){
        lock.lock();
        try {
            if(number > 0) {
                System.out.println(Thread.currentThread().getName()+"\t卖出第"+(number--)+",还剩:"+number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}